//Copyright (C) 2010 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

/*
 * TradesDialog.java
 *
 * Created on Dec 20, 2010, 4:59:47 PM
 */
package org.workplicity.cia.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.workplicity.cia.table.render.BaseTableRenderer;
import org.workplicity.cia.table.TradesTableModel;
import org.workplicity.cia.worklet.ElogsWorklet;
import org.workplicity.elog.entry.ElogUser;
import org.workplicity.elog.entry.Trade;
import org.workplicity.elog.repos.Trades;
import org.workplicity.plugin.cache.Cache.Timing;
import org.workplicity.util.Helper;
import org.workplicity.util.Resources;
import org.workplicity.worklet.WorkletContext;

/**
 * This class implements the trades dialog.
 * @author Ron Coleman
 */
public class TradesDialog extends javax.swing.JDialog {

    private WorkletContext context = ElogsWorklet.getInstance().getContext();
    private ElogUser user = (ElogUser) Helper.whoAmI(context);

    /** Creates new form TradesDialog */
    public TradesDialog(java.awt.Frame parent) {
        super(parent, false);
        initComponents();
        
        this.setLocationRelativeTo(null);

        this.setTitle("Netlog (" + user.getLogname() + ") >> Trades");

        this.setIconImage(Resources.logoSmall.getImage());

        initTradesTable();
    }

    private void initTradesTable() {
        // Fix the column widths
        tradesTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        final int[] WIDTHS = {
             40,  // Id
            110,  // Name
            227,  // Description
        };

        for(int i=0; i < WIDTHS.length; i++) {
            TableColumn col = tradesTable.getColumnModel().getColumn(i);

            col.setPreferredWidth(WIDTHS[i]);
        }

        TableColumnModel cm = this.tradesTable.getColumnModel();

        // Set up the table rendering
        BaseTableRenderer cr = new BaseTableRenderer();

        for (int i = 0; i < tradesTable.getColumnCount(); i++) {
            cm.getColumn(i).setCellRenderer(cr);
        }

        // Add mouse support for the request table
        // See http://mycodepage.blogspot.com/2006/09/how-to-create-double-click-event-on.html
        tradesTable.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    JTable target = (JTable) e.getSource();
                    final int row = target.getSelectedRow();

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            editEntry(row);
                        }
                    });
                }
            }
        });

        TradesTableModel model = (TradesTableModel) this.tradesTable.getModel();

        model.refresh();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tradesTable = new javax.swing.JTable();
        doneButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tradesTable.setModel(new TradesTableModel());
        jScrollPane1.setViewportView(tradesTable);

        doneButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        doneButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/done2.png"))); // NOI18N
        doneButton.setActionCommand("Close");
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\Ron\\Workplicity\\CIAElog\\src\\remove2.png")); // NOI18N
        deleteButton.setToolTipText("Click to remove selected user from the system.");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        addButton.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\Ron\\Workplicity\\CIAElog\\src\\add2.png")); // NOI18N
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        refreshButton.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\Ron\\Workplicity\\CIAElog\\src\\refresh2.png")); // NOI18N
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 174, Short.MAX_VALUE)
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(doneButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(refreshButton, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(addButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(doneButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(deleteButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
        // Refresh the trades cache so that the latest
        // updates are present
        ElogsWorklet.getInstance().getTrades().refresh(Timing.NOW);

        this.dispose();
}//GEN-LAST:event_doneButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        final int row = this.tradesTable.getSelectedRow();

        if (row == -1) {
            return;
        }

        final TradesDialog dialog = this;

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TradesTableModel model = (TradesTableModel) dialog.tradesTable.getModel();

                Trade trade = (Trade) model.getRow(row);

                String msg = "Trade '" + trade + "' will be permanently deleted!!!";
                msg += "\nProceed?";

                int n = JOptionPane.showConfirmDialog(
                        dialog,
                        msg,
                        "Confirm",
                        JOptionPane.YES_NO_OPTION);

                if (n == 1) {
                    return;
                }

                WorkletContext context = ElogsWorklet.getInstance().getContext();

                // First delete the trade
                // NOTE: This may leave some tangling references
                boolean successful = Helper.delete(trade, Trades.TITLE, context);

                if (successful) {
                    msg = "Trade '" + trade + "' deleted from system.";

                    JOptionPane.showMessageDialog(dialog, msg,
                            "Netlog", JOptionPane.INFORMATION_MESSAGE);

                    model.refresh();
                } else {
                    msg = "Delete of trade '" + trade + "' failed.";
                    msg += "\nPerhaps your session expired?";

                    JOptionPane.showMessageDialog(dialog, msg,
                            "Netlog", JOptionPane.ERROR_MESSAGE);

                }
            }
        });
}//GEN-LAST:event_deleteButtonActionPerformed

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        final JDialog parent = this;
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                editEntry(-1);
            }
        });
}//GEN-LAST:event_addButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TradesTableModel model = (TradesTableModel) tradesTable.getModel();

                model.refresh();
            }
        });
}//GEN-LAST:event_refreshButtonActionPerformed

    /**
     * Opens the trade edit dialog
     * @param row Row
     */
    private void editEntry(int row) {
        TradesTableModel model = (TradesTableModel) tradesTable.getModel();

        Trade trade = null;

        if(row < 0)
            trade = new Trade();
        else
        {
            trade = model.getRow(row);
        }

        EditTradeDialog dialog = new EditTradeDialog(this,trade);

        dialog.setVisible(true);

        model.refresh();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TradesDialog dialog = new TradesDialog(new javax.swing.JFrame());
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton doneButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton refreshButton;
    private javax.swing.JTable tradesTable;
    // End of variables declaration//GEN-END:variables
}
